# Copyright 2012 Frank John Bruzzaniti.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import calendar, time, sys, os

def date2ts(date_str): #function converts date strings to timestamps
    time_tuple = time.strptime(date_str, "%Y-%m-%d")
    timestamp_utc = calendar.timegm(time_tuple)
    return int(timestamp_utc * 1000) #pad milliseconds portion of timestamp with 0's

if len(sys.argv) < 3:
    sys.stderr.write('Usage: ' + os.path.basename(sys.argv[0]) + ' CEF_FILE [DATE_RANGE]\n')
    sys.stderr.write('Where DATE_RANGE is YYYY-MM-DD or YYYY-MM-DD..YYYY-MM-DD\n')
    sys.exit(1)

#convert user supplied dates to timestamps
if sys.argv[2].find('..') != -1:
    start_ts = date2ts(sys.argv[2].split('..')[0])
    end_ts = date2ts(sys.argv[2].split('..')[1])
else:
    start_ts = date2ts(sys.argv[2])
    end_ts = 99999999999999 #thought this was cleaner then having another if later. 

srcFILE = open(sys.argv[1],'r')
for line in srcFILE:
    rt_spos = line.find('rt=') + 3 #find start or rt string
    rt_epos = line[rt_spos:].find(" ") + rt_spos #find end of rt string
    rt = int(line[rt_spos:rt_epos]) #assign value to rt to make things more readable later
 
    if rt >= start_ts and rt <= end_ts:
        print line.rstrip()

srcFILE.close()
